#pragma once
#include<iostream>
#include"index.hpp"
#include<vector>
#include<string>
#include"util.hpp"
#include<jsoncpp/json/json.h>
#include<unordered_map>

namespace ns_search
{
    struct InvertedElemForPrint
    {
        uint64_t doc_id;
        int weight;
        std::vector<std::string>words;
        InvertedElemForPrint():doc_id(0),weight(0)
        {}
    };

    class Searcher
    {
    public:
        Searcher():index(nullptr)
        {

        }
        ~Searcher()
        {

        }
        void InitSearch(const std::string& input)
        {
            index = ns_index::Index::GetInstance();
            index->BuildIndex(input);
        }
        //开始查找,需要输入查询关键词
        void search(const std::string& query,std::string* json_string)
        {
            //对需要查找的内容进行分词
            std::vector<std::string>words;
            ns_util::JiebaUtil::CutString(query,&words);
            //分词结果保存在words中
            //根据分词结果查找倒排拉链
            // std::vector<ns_index::InvertedElem> inverted_list_all;
            std::vector<InvertedElemForPrint>inverted_list_all;
            for(auto& word :words)
            {
                std::unordered_map<uint64_t,InvertedElemForPrint> token_map;
                boost::to_lower(word);
                std::vector<ns_index::InvertedElem>* inverted_list = index->GetInvertedList(word);
                if(inverted_list == nullptr)
                {
                    continue;
                }
                // inverted_list_all.insert(inverted_list_all.end(),inverted_list->begin(),inverted_list->end());
                //遍历查询到的结果
                for(auto& elem : *inverted_list)
                {
                    //找到同一个doc_id所对应的元素
                    auto& item = token_map[elem.doc_id];
                    item.doc_id = elem.doc_id;
                    item.weight += elem.weight;
                    item.words.push_back(elem.word);
                }
                for(auto& item:token_map)
                {
                    inverted_list_all.push_back(item.second);
                }

            }
            //对找到的结果进行排序
            // sort(inverted_list_all.begin(),inverted_list_all.end(),[](const ns_index::InvertedElem& e1,
            // const ns_index::InvertedElem& e2)
            // {
            //     return e1.weight > e2.weight;
            // }
            // );
            sort(inverted_list_all.begin(),inverted_list_all.end(),[](const InvertedElemForPrint& e1,
            const InvertedElemForPrint& e2)
            {
                return e1.weight > e2.weight;
            }
            );
            
            //将结果构建成json串
            Json::Value root;
            for(auto& item : inverted_list_all)
            {
                ns_index::DocInfo* doc = index->GetForwardIndex(item.doc_id);
                if(doc == nullptr)
                {
                    continue;
                }
                Json::Value elem;
                elem["title"] = doc->title;
                elem["desc"] = GetDesc(doc->content,item.words[0]);
                elem["url"] = doc->url;
                // elem["id"] = (int)item.doc_id;
                // elem["weight"] = item.weight;
                root.append(elem);
            }
            Json::StyledWriter writer;
            *json_string = writer.write(root);
        }

        std::string GetDesc(const std::string& content,const std::string& word)
        {
            const int prev_step = 50;
            const int next_step = 100;
            auto iter = std::search(content.begin(),content.end(),word.begin(),word.end(),[](int x,int y)
            {
                return std::tolower(x) == std::tolower(y);
            }
            );
            if(iter == content.end())
            {
                return "NONE1";
            }
            int pos = std::distance(content.begin(), iter);

            int start = 0;
            int end = content.size()-1;
            if(pos > start + prev_step) 
            {
                start = pos - prev_step;
            }
            if(pos < end - next_step)
            {
                end = pos + next_step;
            }
            if(start >= end)
            {
                return "NONE2";
            }
            std::string desc = content.substr(start,end - start);
            desc += "....";
            return desc;
        }

    private:
        ns_index::Index* index;
    };

}